package com.younion.action.manage;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Lists;
import com.younion.business.IActiveService;
import com.younion.business.IAdvertisingService;
import com.younion.business.ICardEntityService;
import com.younion.business.ICustomerKindService;
import com.younion.business.ICustomerService;
import com.younion.business.IFavourableEntityService;
import com.younion.business.IMsgTemplateService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.SysConstants;
import com.younion.common.paginator.Paginator;
import com.younion.common.util.ImageFileUtil;
import com.younion.permission.PermissionUtil;
import com.younion.util.UUIDUtil;
import com.younion.vo.CustomerAccountVO;
import com.younion.vo.CustomerKindVO;
import com.younion.vo.CustomerVO;
import com.younion.vo.MsgTemplateVO;

import cpcns.jhsks.util.MapCollectionUtils;

/**
 * @author wells
 */
public class CustomerAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private static final String SELECT_LIST_TYPE = "select";

	protected static final Log logger = LogFactory.getLog(CustomerAction.class);

	private ICustomerService customerService = null;

	private CustomerVO customerVO = new CustomerVO();

	//private ICustomerAccountService customerAccountService = null;

	private CustomerAccountVO customerAccountVO = new CustomerAccountVO();

	private List<CustomerVO> customerList;// 结果集列表

	private String templateId;

	private List<CustomerKindVO> customerKindList;

	private ICustomerKindService customerKindService = null;
	@Autowired
	private IMsgTemplateService msgTemplateService = null;

	private List<String> customers = Lists.newArrayList();
	
	private String searchType;
	
	private String lookUpPre;
	@Autowired
	private IFavourableEntityService favourableEntityService = null;
	@Autowired
	private ICardEntityService cardEntityService = null;
	@Autowired
	private IActiveService activeService = null;
	@Autowired
	private IAdvertisingService advertisingService = null;

	/**
	 * 列表：翻页区；数据区
	 */
	@SuppressWarnings("unchecked")
	@RequiresPermissions("listCustomer")
	public String listCustomer() {
		try {
			Map paramMap = null;
			if (customerVO != null) {
				if (customerVO.getProvince() != null && "-1".equals(customerVO.getProvince().getRegionId().toString())){
					customerVO.setProvince(null);
				}	
				if (customerVO.getCity() != null && "-1".equals(customerVO.getCity().getRegionId().toString())){
					customerVO.setCity(null);
				}
				if (customerVO.getDistrict() != null && "-1".equals(customerVO.getDistrict().getRegionId().toString())){
					customerVO.setDistrict(null);
				}
				if (customerVO.getCustomerKindId() != null &&  customerVO.getCustomerKindId() == -1){
					customerVO.setCustomerKindId(null);
				}
				if(customerVO.getCardTotal()==null){
					customerVO.setCardTotal(0);
				}
				if(getSessionUser().getCustomer() != null){
					customerVO.setId(getSessionUser().getCustomer().getId());
				}
				paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils
						.describe(customerVO));
			}
			// 获取总记录数
			int total = customerService.getCountByMap(paramMap);
			// 根据总记录数获取分页对象
			Paginator paginator = this.getPaginator(total);
			customerList = customerService.get(paramMap, paginator);
			customerKindList = (List<CustomerKindVO>) customerKindService
					.getAll();
			// 保存分页对象
			this.savaPaginator(paginator);
			if (!StringUtils.isEmpty(templateId) && Integer.parseInt(templateId) > 0) {
				MsgTemplateVO msgTemplateVO = msgTemplateService
						.getById(templateId);
				customers = Arrays.asList(msgTemplateVO.getCustomerIds().split(
						PermissionUtil.comma));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		this.addLog(2, "查询商家列表", "查询商家列表", this.getSessionUser());
		return SUCCESS;
	}

	/**
	 * 新增
	 */
	@RequiresPermissions("addCustomer")
	public String addCustomer() {
		UUIDUtil uuidUtil = new UUIDUtil();
		try {
			customerKindList = (List<CustomerKindVO>) customerKindService
					.getAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
		customerVO.setCode("YU" + uuidUtil.getUuid());
		return SUCCESS;
	}
	
	public String viewCustomer() {
		try {
			customerVO = customerService.getById(customerVO.getId().toString());
			CustomerKindVO ckVO = customerKindService.getById(customerVO.getCustomerKindId().toString());
			request.setAttribute("customerKindVO", ckVO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 修改保存，调度Jsp
	 */
	@RequiresPermissions("editCustomer")
	public String editCustomer() {
		try {
			customerKindList = (List<CustomerKindVO>) customerKindService
					.getAll();
			customerVO = customerService.getById(customerVO.getId().toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 保存动作
	 */
	@RequiresPermissions("saveCustomer")
	public String saveCustomer() {
		try {
			// customerVO.setCooperationStaus(0);
			if(customerVO.getMoney() == null)
				customerVO.setMoney(0.0);
			if (this.customerVO.getId() ==null)
				customerVO.setTop(0);
			customerVO = customerService.save(customerVO);
			/*Map paramMap = new HashMap();
			paramMap.put("customerCode", customerVO.getCode());
			int haveAccount = customerAccountService.getCountByMap(paramMap);
			if (haveAccount <= 0) {
				customerAccountVO.setMoney(0D);
				customerAccountVO.setCustomerCode(customerVO.getCode());
				customerAccountService.save(customerAccountVO);
			}*/
			ImageFileUtil.processImageFiles(this.customerVO.getId(), "1", request);
			refresh();
			String id = customerVO.getId() == null ? "" : customerVO.getId().toString();
			String log = "".equals(id) ? "添加商家" : "更新商家";
			int type = "".equals(id) ? 3:4;
			this.addLog(type, log+id, log,getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		request.setAttribute("refreshNavTabId", "customerList");
		return SUCCESS;
	}

	/**
	 * 解除合作
	 */
	@RequiresPermissions("relieveCustomer")
	public String relieveCustomer() {
		try {
			String status = request.getParameter("status");
			String pkId = request.getParameter("ids");
			Map paramMap = new HashMap();
			paramMap.put("cooperationStaus", status);
			paramMap.put("ids", Arrays.asList(pkId.split(",")));
			customerService.updateCooperationStaus(paramMap);
			refresh();
			String log = "解除商家合作";
			this.addLog(5, log+pkId, log,getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		request.setAttribute("refreshNavTabId", "customerList");
		return SUCCESS;
	}
	
	/**
	 * 恢复合作
	 */
	@RequiresPermissions("regainCustomer")
	public String regainCustomer() {
		try {
			String status = request.getParameter("status");
			String pkId = request.getParameter("ids");
			Map paramMap = new HashMap();
			paramMap.put("cooperationStaus", status);
			paramMap.put("ids", Arrays.asList(pkId.split(",")));
			customerService.updateCooperationStaus(paramMap);
			refresh();
			String log = "恢复商家合作";
			this.addLog(5, log+pkId, log,getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		request.setAttribute("refreshNavTabId", "customerList");
		return SUCCESS;
	}
	
	/**
	 * 删除鿴
	 */
	@RequiresPermissions("deleteCustomer")
	public String deleteCustomer() {
		try {
			String ids = request.getParameter("ids");
			Map<String,Integer> map = new HashMap<String,Integer>();
			List<String> customerIds = Arrays.asList(ids.split(","));
			System.out.println("customerIds====="+customerIds.size());
			//优惠券图片路径
			String fav_realPath = request.getSession().getServletContext().getRealPath(
					SysConstants.FavourableEntity_IMG_PATH);
			favourableEntityService.deleteImgByCustomerIds(customerIds, fav_realPath);
			//会员卡图片路径
			String card_realPath = request.getSession().getServletContext().getRealPath(
					SysConstants.CARD_IMG_PATH);
			cardEntityService.deleteImgByCustomerIds(customerIds, card_realPath);
			//活动图片路径
			String active_realPath = request.getSession().getServletContext().getRealPath(
					SysConstants.ACTIVE_IMG_PATH);
			activeService.deleteImgByCustomerIds(customerIds, active_realPath);
			//广告图片路径
			String advertise_realPath = request.getSession().getServletContext().getRealPath(
					SysConstants.ADVERTISING_IMG_PATH);
			advertisingService.deleteImgByCustomerIds(customerIds, advertise_realPath);
			
			//删除模板中对应的customerId
			msgTemplateService.updateCustomerIds(customerIds);
			customerService.removeByIdsRelated(customerIds);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;

	}
	
	public String updateTopCustomer() {
		try {
			Map<String, Integer> map = new HashMap<String, Integer>();
			map.put("id", this.customerVO.getId());
			Integer maxTop = this.customerService.selectMaxTop();
			map.put("maxTop", maxTop + 1);
			this.customerService.updateTopById(map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		refresh();
		return SUCCESS;
	}

	private void refresh(){
		request.setAttribute("refreshNavTabId", "customerList");
		request.setAttribute("callbackType", "forward");
		request.setAttribute("forwardUrl", request.getContextPath()+"/customer/listCustomer.action");
	}
	
	public CustomerVO getCustomerVO() {
		return customerVO;
	}

	public void setCustomerVO(CustomerVO customerVO) {
		this.customerVO = customerVO;
	}

	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public List<CustomerVO> getCustomerList() {
		return customerList;
	}

	public void setCustomerList(List<CustomerVO> customerList) {
		this.customerList = customerList;
	}

	public void setCustomerAccountVO(CustomerAccountVO customerAccountVO) {
		this.customerAccountVO = customerAccountVO;
	}

	/*public void setCustomerAccountService(
			ICustomerAccountService customerAccountService) {
		this.customerAccountService = customerAccountService;
	}*/


	public void setMsgTemplateService(IMsgTemplateService msgTemplateService) {
		this.msgTemplateService = msgTemplateService;
	}

	public List<String> getCustomers() {
		return customers;
	}

	public void setCustomers(List<String> customers) {
		this.customers = customers;
	}

	public List<CustomerKindVO> getCustomerKindList() {
		return customerKindList;
	}

	public void setCustomerKindList(List<CustomerKindVO> customerKindList) {
		this.customerKindList = customerKindList;
	}

	public void setCustomerKindService(ICustomerKindService customerKindService) {
		this.customerKindService = customerKindService;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}

	public String getLookUpPre() {
		return lookUpPre;
	}

	public void setLookUpPre(String lookUpPre) {
		this.lookUpPre = lookUpPre;
	}

	public String getTemplateId() {
		return templateId;
	}

	public void setTemplateId(String templateId) {
		this.templateId = templateId;
	}

	public void setFavourableEntityService(
			IFavourableEntityService favourableEntityService) {
		this.favourableEntityService = favourableEntityService;
	}

	public void setCardEntityService(ICardEntityService cardEntityService) {
		this.cardEntityService = cardEntityService;
	}

	public void setActiveService(IActiveService activeService) {
		this.activeService = activeService;
	}

	public void setAdvertisingService(IAdvertisingService advertisingService) {
		this.advertisingService = advertisingService;
	}

}